<!--
 * @Description: 分解目标成本数据
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2024-03-01 18:34:04
 * @LastEditTime: 2024-03-25 14:15:14
 * @FilePath: \cscec-pms-admin\src\views\businessAffairs\businessCostPlanManagement\costPlanManagement\costPlan\components\InformationInit\components\DecompositionData\index.vue
-->
<template>
  <div class="table-wrapper">
    <a-form-model style="margin:16px 0 0 -30px" ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules">
    <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
       <!-- 附件上传 -->
       <template #fileList>
              <template v-if="editModel != 0">
                <l-table
                  businessCode="BM27"
                  :uploadArrys.sync="form.fileList"
                ></l-table>
                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
              </template>
              <file-link
                v-else
                :fileList="form.fileList"
                style="margin-top: -3px"
              ></file-link>
            </template>
      </custom-form>
      </a-form-model>
    <u-table
        ref="table"
        fixed-columns-roll
        :height="height"
        show-header-overflow
        :tree-config="{
            children: 'children',
            expandAll: true
        }"
        row-id="id"
        :use-virtual="true"
        border
        :row-height="40"
      >
        <u-table-column
        v-for="item in columns"
        :key="item.dataIndex"
        :prop="item.dataIndex"
        :label="item.title"
        :width="item.width"
        :minWidth="item.minWidth"
        :fixed="item.fixed"
        :tree-node="item.dataIndex === 'name'"
        align="left"
        >
        <template v-slot="{ row }">
          <template v-if="(row.yearMonths || []).findIndex((el) => el.key === item.dataIndex) >= 0">
            <p v-if="(row.children || []).length > 0" :title="row.detailValues[item.dataIndex]">{{ row.detailValues[item.dataIndex]  | setPlaceholder }}</p>
            <input
              class="input-style"
              v-else
              type="number"
              v-model="row.detailValues[item.dataIndex]"
              @input="handleUpdate(row, item.dataIndex, item.dataIndex)"
            />
          </template>
          <template v-else-if="item.dataIndex === 'description'">
            <BaseInput v-model="row[item.dataIndex]" @blur="handleUpdate(row, item.dataIndex)" />
          </template>
          <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex]| setPlaceholder }}</p>
        </template>
      </u-table-column>
      </u-table>
    <!-- 选择审批人 -->
    <selectApprover :business-id="businessId" :process-config="setProcessConfig" :is-close-upper="false" @close="submitApproval" />
    <!-- 选择审批人 -->
  </div>
</template>
<script>
  import { UTable, UTableColumn } from 'umy-ui'
import { columns } from './model.js'
import { getCostPlan as queryPlan, addOrUpdateProjectTreeDetail, submit,uploadPlanFile} from '@/api/businessAffairs/costAccountInit'
import debounce from 'lodash/debounce'
import { publicMixin } from './../../../public'
import { placeholder } from '../../../../../../headquartersDashboard/components/placeholderWay.js'
export default {
  name: 'DecompositionData',
  mixins: [publicMixin], //混入文件
  components: {
    UTable,
    UTableColumn
  },
  data() {
    return {
      // 表格高度
      height: 0,
      // 表格数据
      data: [],
      // 表格数据映射
      dataMap: new Map(),
      // 表头
      columns: this.$clone(columns),
      // 动态表头
      activeColumns: [],
      // 当前项目id
      projectId: this.$userInfo()?.currentPost?.projectId,
      // 业务id
      businessId: '',
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      form:{},
      editModel:1,
      rules: {
        fileList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }],
        }
    }
  },
  async created() {
    // 获取流程配置值
    this.processConfig = await this.$getConfigFn('com_business_cost_project_plan')
  },
  filters:{
    setPlaceholder(val){
      return placeholder(val)
    }
  },
  computed:{
    formList() {
      return [
        {
          slot: true,
          keyName: 'fileList',
          label: '佐证材料',
          span: 24
        }
      ]
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileList'() {
      if (this.editModel != 0) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileList')
        })
      }
    },
  },
  mounted() {
    this.height = document.querySelector('.table-wrapper').offsetHeight
    this.getTableData()
  },
  methods: {
    /**
     * @description: 扁平化树
     * @param {array} tree 树
     * @return {void}
     */
    flattenTree(tree) {
      for (let i = 0; i < tree.length; i++) {
        this.dataMap.set(tree[i].id, tree[i])
        if (tree[i]?.childTree && tree[i].childTree?.length > 0) {
          this.flattenTree(tree[i].childTree)
        }
      }
    },
    /**
     * @description: 获取表格数据
     * @return {void}
     */
    getTableData() {
      this.$emit('update:spinning', true)
      queryPlan({
        projectId: this.projectId,
        isHide: true
      })
        .then((res) => {
          if (res.code === '0') {
            this.businessId = res.data.id
            this.data = res.data?.trees
            this.activeColumns = res.data.yearMonths.map((el) => {
              return {
                title: el.title,
                width: 120,
                dataIndex: el.key
              }
            })
            const col = this.$clone(columns)
            const end = col.pop()
            this.columns = [...col, ...this.activeColumns, end]
            this.$nextTick(() => {
              this.summation(this.data,this.activeColumns)
              this.reloadData(this.data)
            })
          }
        })
        .finally(() => {
          this.$emit('update:spinning', false)
        })
    },
    /**
     * @description: 加载数据
     * @param {array} data
     * @return {void}
     */
     reloadData(data) {
      //this.flattenTree(data)
        // 获取之前展开数据
        const expandRecords = this.$refs.table.getTreeExpandRecords()
      // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
      const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
      const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
        // 加载数据
        this.$refs.table.reloadData(data).then(() => {
          // 数据加载完成出现之后，打开之前的展开行
          expandRecords.forEach((row) => {
          this.$refs.table.setTreeExpansion(row, true)
        })
          this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
        })
      },
    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @param {string} blurIndex 失焦字段
     * @return {void}
     */
    handleUpdate: debounce(function (row, blurIndex, key) {
      if(blurIndex!='description'){
        row.detailValues[blurIndex] =  row.detailValues[blurIndex]?.replace(/^(-)*(\d+)\.(\d\d).*$/,"$1$2.$3");
      }
      addOrUpdateProjectTreeDetail(
        blurIndex === 'description'
          ? {
              id: row.id,
              description: row.description
            }
          : {
              amount: row.detailValues[blurIndex],
              id: row.id,
              yearMonthNum: blurIndex,
              yearMonthStr: this.moment(blurIndex).format('YYYY年MM月')
            }
      )
      if (key) {
        let changeTreeData = this.changeTreeDataTwo(this.data, row, key)
        this.$nextTick(() => {
          this.reloadData(changeTreeData)
        })
      }
    }, 500),
    /**
     * @description: 提交
     * @return {promise}
     */
    handleSubmit() {
      let fileParam = {
        projectId:this.projectId
      },
      fileId = [];
      return new Promise((resolve, reject) => {
        this.setProcessConfig = null
        this.$refs.ruleForm.validate((e) => {
        if(e){
          console.log(this.form,2222)
          return
        this.submitApprovalConfirm(this.processConfig, (flag) => {
          if (!flag) return
          this.$emit('update:spinning', true)
          submit(this.businessId)
            .then((res) => {
              if (res.data.length === 0) {

                this.$emit('update:spinning', false)
                this.setProcessConfig = this.processConfig
                // 特殊处理弹窗下一步
                if (this.processConfig === 4) {
                  this.$emit('submitApproval', true)
                }
                resolve()
              } else {
                this.$emit('update:spinning', false)
                if (this.processConfig === 4) {
                  this.$emit('submitApproval', false)
                }
                reject(res.data)
              }
            })
            .catch((err) => {
              console.log(err)
              this.$emit('update:spinning', false)
              reject(err)
            })
        })
      }else{
          reject('请选择佐证材料')
      }
      })
    })
    },
    /**
     * @description: 提交选择审批人之后
     * @param {boolean} val true确认审批，否则取消
     * @return {promise}
     */
    submitApproval(val) {
      this.$emit('submitApproval', val)
    }
  }
}
</script>
<style lang="less" scoped>
.input-style {
  width: 100%;
  height: 30px;
  padding: 0 11px;
  text-align: left;
  background-color: transparent;
  border: 0;
  border-radius: 2px;
  outline: 0;
  border: 1px solid #d9d9d9;
}
.input-style:focus {
  border: 1px solid #40a9ff;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
  /* 针对Firefox */
input[type=number] {
  -moz-appearance: textfield;
}
</style>
